package interfaz;

import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observable;
import java.util.Observer;

import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import commons.IAplicacionLocal;

import mundo.P2P;

public class PanelMisAplicaciones extends JPanel implements Observer, ActionListener, ListSelectionListener
{
	public final static String[] HEADERS = { "Nombre", "Parametros", "Puerto" };
	
	private JTable tabla;
	private InterfazP2P interfaz;
	private JButton btnAgregar;
	private JButton btnEliminar;
	private DefaultTableModel model;
	
	public PanelMisAplicaciones( InterfazP2P i )
	{
		setLayout( new BorderLayout( ) );
		interfaz = i;
		
		model = new DefaultTableModel( HEADERS, 0 ) {
	        public boolean isCellEditable(int rowIndex, int mColIndex) {
	            return false;
	        }
	    };

		tabla = new JTable( model );
		tabla.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
		tabla.setShowGrid( false );
		JScrollPane scrollPane = new JScrollPane( tabla );
		tabla.setFillsViewportHeight( true );
		
		tabla.getColumnModel().getColumn(0).setPreferredWidth( 250 );
		tabla.getColumnModel().getColumn(1).setPreferredWidth( 350 );
		tabla.getColumnModel().getColumn(2).setPreferredWidth( 100 );
		tabla.getSelectionModel().addListSelectionListener( this );


		btnAgregar = new JButton( "Agregar Aplicacion" );
		btnAgregar.addActionListener( this );
		btnAgregar.setActionCommand( "AGREGAR" );
		
		btnEliminar = new JButton( "Eliminar Aplicacion" );
		btnEliminar.addActionListener( this );
		btnEliminar.setActionCommand( "ELIMINAR" );
		btnEliminar.setEnabled( false );
		
		add( scrollPane, BorderLayout.CENTER );
		JPanel panel = new JPanel( );
		panel.add( btnAgregar );
		panel.add( btnEliminar );
		add( panel, BorderLayout.SOUTH );
	}
	
	@Override
	public void update( Observable p2p, Object arg1 ) 
	{
		String[][] aps = ((P2P)p2p).darLocales();
		
		for( int i = 0, j = model.getRowCount(); i < j ; i++ )
			model.removeRow( 0 );
		
		for( int i = 0; i < aps.length ; i++ )
			model.insertRow( i, aps[ i ] );
	}

	@Override
	public void actionPerformed(ActionEvent e) 
	{
		String cmd = e.getActionCommand();
		if( cmd.equals("AGREGAR") )
			interfaz.mostrarDialogoAgregarAplicacion( );
		else if( cmd.equals("ELIMINAR") )
		{
			interfaz.eliminarAplicacion( (String)model.getValueAt( tabla.getSelectedRow(), 0 ) );
			btnEliminar.setEnabled( false );
		}
	}

	@Override
	public void valueChanged( ListSelectionEvent e ) 
	{
		int fila = e.getFirstIndex();
		if( fila >= 0 )
			btnEliminar.setEnabled( true );
		else
			btnEliminar.setEnabled( false );
	}
}
